// subPackages/pages/HousingActivity/HousingChiXiaoMy/HousingChiXiaoMy.js
import Serv from './myOrderListServ';
import Config from '../../../utils/config2.js'
import util from '../../../utils/util'
import util2 from '../../../utils/util2'

var timer = require('./../../../utils/wxTimer.js');
var regeneratorRuntime = require("../../../lib/js/runtime-module.js");
const App = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tabIndex:0,
    noStatus:false,
    orderList:[],
    wxTimerList:{}
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.stopPullDownRefresh()
    this.questUserOrderData()
  },
  
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    this.clearwxTimer();
  },
  /**
   * 清除定时器
   */
  clearwxTimer(){
    let { orderList } = this.data;
    orderList.forEach((item)=>{
        if( item.wxTimer)item.wxTimer.stop();
    });
  },
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    this.clearwxTimer();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.clearwxTimer();
    this.show()

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 切换状态
   */
  changeTab(e){
    let { tabindex} = e.currentTarget.dataset
    this.setData({
      status:tabindex,
      tabIndex:tabindex,
      noStatus:false,
      orderList:[]
    });
    this.questUserOrderData();
  },
  /**
  * 跳转产品详情
  */
 goProductDetails(e){
  let businessId = e.currentTarget.dataset.projectid;
   wx.navigateTo({ url: `/subPackages/pages/buildingDetail/buildingDetail?projectId=${businessId}` })
},

  /**
   * 请求用户订单
   */
  async questUserOrderData () {
    //status 状态 0：全部订单  1：待支付  2：已支付  3：已失效
    //订单类型 0 空开盘 1认购，2认筹 3小订 
    let param = {
      mobile:wx.getStorageSync(Config.phoneNoKey),
      status:this.data.tabIndex
    }
    wx.showLoading({
      title: '加载中',
    })
    let that = this;
    let nowTime = new Date().getTime();
    let request = await Serv.getUserOrder(param);
    let nowTime2 = new Date().getTime();
    let time = nowTime2 - nowTime;
    let nowTT = request.timestamp + time;
    wx.hideLoading()
    if(request.result.length==0){
       that.setData({noStatus:true});
       return false;
    }
  
    if (request.success && request.result) {
      let result = request.result;
      result.length>0&&result.forEach((ele,index) => {
        if(ele.orderTime){
          let mydata=ele.orderTime.replace(/-/g, '/');  
          if(ele.roomName){
            var str =ele.roomName.replace(/\-/, "&").split('&');
            ele.roomName =str.length>1?str[1]:str[0];
          }
          
          let endTime = new Date(new Date(mydata).setMinutes(new Date(mydata).getMinutes() + 30)).getTime();
          let countdownTime = util2.dayTo(endTime,nowTT); 
          if(ele.type==2){ //认筹的
            if(ele.orderStatus==0){  
              ele.wxTimer = new timer({
                beginTime: '00:'+countdownTime.min+':'+countdownTime.sec,
                name:'wxTimer'+index,
                complete:function(){
                  ele.orderStatus = 3
                  that.setData({
                    wxTimerList:{}
                  });
                  that.clearwxTimer();
                  console.log("完成了")
              },
            })
              ele.wxTimer.start(this);
          }
           }else{ //认购与小订
            if(ele.orderStatus!=2&&ele.downPaymentStatus==1){  
              ele.wxTimer = new timer({
                beginTime: '00:'+countdownTime.min+':'+countdownTime.sec,
                name:'wxTimer'+index,
                complete:function(){
                  ele.downPaymentStatus =1;
                  ele.orderStatus =2;
                  that.setData({
                    wxTimerList:{}
                  });
                  that.clearwxTimer();
                  console.log("完成了")
              },
            })
              ele.wxTimer.start(this);
          }
           }

        }
        
      });
      let projectIds = result.map((item)=>item.projectId);
      this.getProductDetailAll(projectIds,result)
      
    }
  },
 /**
  * 批量获取美房详情
  */
 async getProductDetailAll(projectIds,result){
    let data = await Serv.getProductDetailProjectId(projectIds)
    result.forEach((item)=>{
       let isExist = data.findIndex((f)=>item.projectId==f.projectId);
       if(isExist>=0){
        item.productId= data[isExist].productId;
        item.coveImg = data[isExist].fileName;
        item.name = data[isExist].name;
        item.cityName = data[isExist].cityName;
        item.provinceName = data[isExist].provinceName;
       }
    });
    this.setData({
      orderList: result
          })

  },
  /**
   * 订单详情Action
   */
  orderListTapAction(event) {
    let index = event.currentTarget.dataset.index
    let {id,downPaymentStatus,orderStatus,activityId,type} = this.data.orderList[index]
    //2020/03/13
    // if(downPaymentStatus!=0 && orderStatus==2){
    //   return false;
    // }
    wx.navigateTo({
      url: `/subPackages/pages/HousingActivity/HousingChiXiaoOrderDetail/HousingChiXiaoOrderDetail?id=${id}&&type=${type}`
    })
  }
})
